package cn.com.base.sys.common;

import java.io.PrintWriter;
import java.io.StringWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;

import cn.com.base.sys.exception.BaseException;
import cn.com.base.sys.exception.NoAdminException;
import cn.com.base.sys.exception.NoLoginException;
import cn.com.base.sys.util.Strings;

public class CustomExceptionResolver extends SimpleMappingExceptionResolver {
	
	

	@Override
	protected ModelAndView doResolveException(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex) {
		String url="";
		String message="";
		Boolean isRedirect=false;
		
		ex.printStackTrace();
		if(ex instanceof BindException){
			BindException bindException=(BindException)ex;
			message= bindException.getFieldError().getDefaultMessage();
		}else if(ex instanceof NoLoginException ){
			   isRedirect=true;
			url="login.do";
			message=  ex.getMessage();
		}
		else if(ex instanceof NoAdminException){
			   isRedirect=true;
			url="adminLogin.jsp";
			message=  ex.getMessage();
		}else if(ex instanceof BaseException){
			url="error";
			message=  ex.getMessage();
		}else{
			 try {
				   isRedirect=false;
		            StringWriter sw = new StringWriter();
		            PrintWriter pw = new PrintWriter(sw);
		            ex.printStackTrace(pw);
		            message= sw.toString() ;
		        } catch (Exception e2) {
		        	message= "";
		        	url="error";
		        }
		}
		ModelAndView modelAndView=new ModelAndView();
		modelAndView.setViewName("outException");
		modelAndView.addObject("url", url);
		modelAndView.addObject("isRedirect", isRedirect);
		modelAndView.addObject("message",message);
		return modelAndView;
	}
}
